package com.xs.ahoi.hcxs.utils;

import com.xs.ahoi.hcxs.model.vo.SearchDataVo;

import java.util.ArrayList;
import java.util.List;

/**
 * author: cdfuhuichao
 * date: 2019/2/14 14:56
 * description:
 */
public class SearchUtil {

    // 搜索
    public static List<SearchDataVo> search(int startMbbIndex, long totalLength, String paraText, String search) {
        String tempPara = paraText;
        List<SearchDataVo> result = new ArrayList<>();
        int i;
        SearchDataVo vo;
        while ((i = tempPara.indexOf(search)) > -1) {
            tempPara = tempPara.replaceFirst(search, getReplaceHolder(search));
            String words = getNearByWords(paraText, search, i, 40);

            // 计算进度百分比，生成vo
            String percent = ObjectUtils.toFix(startMbbIndex * 100f / totalLength, 2) + "%";
            vo = new SearchDataVo(startMbbIndex, words, percent, search, i - paraText.indexOf(words));
            result.add(vo);
        }
        if (result.size() > 0) {
            return result;
        }
        return null;
    }

    // 获取临时替换占位符
    public static String getReplaceHolder(String search) {
        StringBuilder replace = new StringBuilder();
        for (int i = 0; i < search.length(); i++) {
            replace.append("x");
        }
        return replace.toString();
    }

    // 截取搜索文字下标前后共{length}个字，搜索的文字长度不能超过length
    public static String getNearByWords(String paraText, String search, int index, int length) {
        int before, after, start, end;

        // 计算前后各需要拼接多少字
        int beforeAndAfter = length - search.length();
        before = beforeAndAfter / 2;
        after = beforeAndAfter - before;

        // 计算截取首尾下标
        if (index < before) {
            start = 0;
            end = length;
        } else {
            start = index - before;
            end = index + search.length() + after;
        }
        if (end > paraText.length()) {
            end = paraText.length();
        }

        return paraText.substring(start, end);
    }

}
